use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use regex::Regex;

mod time_conversion;
use time_conversion::convert_time_to_milliseconds;

fn srt_to_smi(input_file: &str, output_file: &str) -> std::io::Result<()> {
    let input = File::open(input_file)?;
    let reader = BufReader::new(input);
    let output = File::create(output_file)?;
    let mut writer = std::io::BufWriter::new(output);
    let mut in_subtitle = false;
    let mut start_time = "99999999".to_string(); // 初始化为字符串
    let mut end_time = "99999999".to_string(); // 初始化为字符串

    let timestamp_regex = Regex::new(r"^\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+$").unwrap();
    writeln!(&mut writer, "<SAMI>\n<HEAD>\n<STYLE TYPE=\"text/css\">\n<!--\nP {{ font-size:16pt; text-align:center; }}\n-->\n</STYLE>\n</HEAD>\n<BODY>\n")?;
    for line in reader.lines() {
        let line = line?;
        let trimmed_line = line.trim();

        if trimmed_line.is_empty() {
            if in_subtitle {
                // End of subtitle
                write!(
                    &mut writer,
                    "<SYNC Start={}>&nbsp;\n",
                    start_time
                )?;
                in_subtitle = false;
            }
        } else if timestamp_regex.is_match(&trimmed_line) {
            // This line is a time stamp
            in_subtitle = true;
            let timestamps: Vec<&str> = trimmed_line.split(" --> ").collect();
            let start_ms = convert_time_to_milliseconds(timestamps[0])?; // 使用 convert_time_to_milliseconds 解析时间戳
            let end_ms = convert_time_to_milliseconds(timestamps[1])?; // 使用 convert_time_to_milliseconds 解析时间戳
            start_time = start_ms.to_string(); // 将毫秒表示转换为字符串
            end_time = end_ms.to_string(); // 将毫秒表示转换为字符串

        } else {
            if in_subtitle {
                // Write the subtitle text
                write!(&mut writer, "<SYNC Start={}>", start_time)?;
                writeln!(&mut writer, "{}", trimmed_line)?;
                write!(
                    &mut writer,
                    "<SYNC Start={}>&nbsp;\n",
                    end_time
                )?;
                in_subtitle = false;
            }
        }
    }
    // Write SMI file footer
    writeln!(&mut writer, "</BODY>\n</SAMI>")?;

    Ok(())
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() != 2 {
        eprintln!("Usage: {} input.srt", args[0]);
        std::process::exit(1);
    }

    let input_file = &args[1];
    let output_file = format!("{}.smi", input_file.trim_end_matches(".srt"));

    if let Err(err) = srt_to_smi(input_file, &output_file) {
        eprintln!("Error: {:?}", err);
        std::process::exit(1);
    }

    println!("Conversion complete. SMI file saved as {}", output_file);

    // let input_file = "/home/h/RustroverProjects/str_to_smi/第1集.srt";
    // let output_file = format!("{}.smi", input_file);
    //
    // if let Err(err) = srt_to_smi(input_file, &output_file) {
    //     eprintln!("Error: {:?}", err);
    //     std::process::exit(1);
    // }
    //
    // println!("Conversion complete. SMI file saved as {}", output_file);
}
